package world.xuewei.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import world.xuewei.dao.CommodityDao;
import world.xuewei.model.entity.Commodity;
import world.xuewei.service.CommodityService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 商品表(Commodity)表服务实现类
 *
 * @author makejava
 * @since 2024-11-16 15:40:06
 */
@Slf4j
@Service("commodityService")
public class CommodityServiceImpl implements CommodityService {
    @Resource
    private CommodityDao commodityDao;

    //获取所有商品
    @Override
    public List<Commodity> getallcommodity(){
        return commodityDao.getallcommodity();
    }

    //热门商品
    @Override
    public List<Commodity> getTopSalesCommodities() {
        return commodityDao.getTopSalesCommodities();
    }


    //根据商品id获取商品信息
    @Override
    public List<Map<String, Object>> getSpecifications(Long commodityId) {
        List<Map<String, Object>> specs = commodityDao.getSpecifications(commodityId);
        // 处理JSON字符串
        for (Map<String, Object> spec : specs) {
            Object specValues = spec.get("specValues");
            if (specValues instanceof String) {
                try {
                    ObjectMapper mapper = new ObjectMapper();
                    Map<String, Object> values = mapper.readValue((String) specValues, Map.class);
                    spec.put("specValues", values.get("values"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return specs;
    }


    //商家添加新商品
    @Override
    @Transactional
    public boolean addProduct(Commodity product){
        try {
            List<Commodity> selectBywhere = commodityDao.selectbywhere(product);
            if (selectBywhere!= null && !selectBywhere.isEmpty()) {
                throw new RuntimeException("已有该名称的商品");
            }else {
                //  插入商品
                commodityDao.addcommdity(product);
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException("新增商品失败：" + e.getMessage());
        }
    }



    // 修改商品信息
    @Override
    public boolean updateProductInformation(Commodity commodity) {
        try {
            // 更新商品信息
            commodityDao.update(commodity);
            return true;
        }catch (Exception e){
            throw new RuntimeException("修改信息失败：" + e.getMessage());
        }
    }

    // 新增商品库存
    @Override
    @Transactional
    public boolean addInventory(Long id, Integer quantity) {
        if (quantity <= 0) {
            throw new RuntimeException("增加的库存数量必须大于0");
        }

        // 查询商品是否存在
        Commodity commodity = commodityDao.queryById(id);
        if (commodity == null) {
            throw new RuntimeException("商品不存在");
        }

        try {
            int rows = commodityDao.addInventory(id, quantity);
            return rows > 0;
        } catch (Exception e) {
            log.error("增加商品库存失败", e);
            throw new RuntimeException("增加库存失败：" + e.getMessage());
        }
    }

    // 商品下架
    @Override
    @Transactional
    public boolean offline(Long id) {
        // 查询商品是否存在
        Commodity commodity = commodityDao.queryById(id);
        if (commodity == null) {
            throw new RuntimeException("商品不存在");
        }

        if (commodity.getStatus() == 0) {
            throw new RuntimeException("商品已下架");
        }

        try {
            int rows = commodityDao.offline(id);
            return rows > 0;
        } catch (Exception e) {
            log.error("商品下架失败", e);
            throw new RuntimeException("商品下架失败：" + e.getMessage());
        }
    }


    // 商品上架
    @Override
    @Transactional
    public boolean online(Long id) {
        // 查询商品是否存在
        Commodity commodity = commodityDao.queryById(id);
        if (commodity == null) {
            throw new RuntimeException("商品不存在");
        }

        if (commodity.getStatus() == 1) {
            throw new RuntimeException("商品已上架");
        }

        try {
            int rows = commodityDao.online(id);
            return rows > 0;
        } catch (Exception e) {
            log.error("商品上架失败", e);
            throw new RuntimeException("商品上架失败：" + e.getMessage());
        }
    }



    // 商品收藏
    @Override
    @Transactional
    public boolean addFavorite(Long userId, Long commodityId) {
        // 查询商品是否存在
        Commodity commodity = commodityDao.queryById(commodityId);
        if (commodity == null) {
            throw new RuntimeException("商品不存在");
        }

        try {
            // 先查询是否已收藏
            List<Commodity> favorites = commodityDao.queryFavorites(userId);
            boolean hasCollected = favorites.stream()
                    .anyMatch(item -> item.getId().equals(commodityId));

            if (hasCollected) {
                // 如果已收藏,则取消收藏
                return !(commodityDao.removeFavorite(userId, commodityId) > 0);
            } else {
                // 如果未收藏,则添加收藏
                return commodityDao.addFavorite(userId, commodityId) > 0;
            }
        } catch (Exception e) {
            log.error("收藏操作失败", e);
            throw new RuntimeException("收藏操作失败：" + e.getMessage());
        }
    }

    // 获取全部收藏
    @Override
    public List<Commodity> queryFavorites(Long userId) {
        return commodityDao.queryFavorites(userId);
    }







    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Commodity queryById(Long id) {
        return this.commodityDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param commodity   筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<Commodity> queryByPage(Commodity commodity, PageRequest pageRequest) {
        long total = this.commodityDao.count(commodity);
        return new PageImpl<>(this.commodityDao.queryAllByLimit(commodity, pageRequest), pageRequest, total);
    }



    /**
     * 新增数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public Commodity insert(Commodity commodity) {
        this.commodityDao.insert(commodity);
        return commodity;
    }

    /**
     * 修改数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public Commodity update(Commodity commodity) {
        this.commodityDao.update(commodity);
        return this.queryById(commodity.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.commodityDao.deleteById(id) > 0;
    }
}
